#include "dealmsgpacket.h"

#include <iostream>
#include <QGuiApplication>
#include <QSettings>
#include <QFile>
#include <QImage>
#include <QDebug>
#include <QUrl>
#include <QCryptographicHash>  //md5加密的库
#include <QBuffer>
#include "./beans/imageprovider.h"

DoDataThread::DoDataThread(QObject *parent):QObject(parent),
    m_WebSocket(std::make_shared<QWebSocket>()),
    m_Timer(new QTimer(this))
{
    //qDebug() << QGuiApplication::applicationDirPath();

    //获取程序文件的路径
    QString path = QGuiApplication::applicationDirPath();
    QString configFile = path + "/config.ini";
    QSettings setting(configFile,QSettings::IniFormat);

    //查看配置文件是否存在
    QFile file(configFile);
    if(!file.exists()){
        setting.setValue("server/ip","127.0.0.1");
        setting.setValue("server/port","2000");
        setting.sync();
    }

    //获取websocket客户端的ip和port
    QString ip = setting.value("server/ip","127.0.0.1").toString();
    QString port = setting.value("server/port","10000").toString();

    //打开websocket
    QString requestUrl = QString("ws://%1:%2").arg(ip).arg(port);
    m_ServerUrl = QUrl(requestUrl);
    m_WebSocket->open(m_ServerUrl);

    m_Thread = new std::thread(&DoDataThread::run,this);
    m_Thread->detach();

    __initSlots();
}

DoDataThread::~DoDataThread(){

    m_MsgQueue.empty();
    m_WebSocket->close();
    m_WebSocket = nullptr;

    if(!m_Thread->joinable()){
        delete m_Thread;
        m_Thread = NULL;
    }
}

void DoDataThread::sendMsg(const QString &msg){
    std::unique_lock<std::mutex> lock(m_Mutex);
    m_MsgQueue.push(msg);

    if(is_Waiting){
        m_Condition.notify_all();
        is_Waiting = false;
    }
    //qDebug() << "push: " << msg ;
}

void DoDataThread::doMessage(QString msg){
    //发送消息
    m_WebSocket->sendTextMessage(msg);
    m_WebSocket->flush();
}

void DoDataThread::__initSlots(){
    connect(m_WebSocket.get(),SIGNAL(connected()),this,SLOT(onConnected()));
    connect(m_WebSocket.get(),SIGNAL(disconnected()),this,SLOT(closeConnection()));
    connect(m_WebSocket.get(),&QWebSocket::textMessageReceived,this,&DoDataThread::onTextMessageReceived);
    connect(m_WebSocket.get(),&QWebSocket::binaryMessageReceived,this,&DoDataThread::doBinaryMessage);
    connect(this,&DoDataThread::onMessage,this,&DoDataThread::doMessage);
    connect(m_Timer,&QTimer::timeout,this,[&]{
        m_WebSocket->open(m_ServerUrl);
    });
    m_Timer->start(1500);
}

void DoDataThread::run(){
    while(1){
        std::unique_lock<std::mutex> lock(m_Mutex);
        if(m_MsgQueue.size() <= 0){
            is_Waiting = true;
            m_Condition.wait(lock,[&]{ return m_MsgQueue.size() > 0;});
        }
        QString msg = m_MsgQueue.front();
        emit onMessage(msg);
        //队列消息弹出
        m_MsgQueue.pop();

        qDebug() << "client send : \n" << msg;
    }
}

void DoDataThread::onConnected(){
    m_Timer->stop();
    emit onNetConnect(true);

    qDebug() << "connect to server !";
}

void DoDataThread::closeConnection(){
    m_Timer->start();
    emit onNetConnect(false);

    qDebug() << "closeConnection !";
}

void DoDataThread::onTextMessageReceived(QString msg){
    emit onCallBack(msg);
}

void DoDataThread::doBinaryMessage(const QByteArray& data){
    emit onCallBinaryBack(data);
}

/*****************************************************************/

MsgControl::MsgControl(QObject *parent) : QObject(parent),
    m_DoDataThread(std::make_shared<DoDataThread>())
{
    connect(m_DoDataThread.get(),&DoDataThread::onCallBack,this,&MsgControl::doCallBack);
    connect(m_DoDataThread.get(),&DoDataThread::onCallBinaryBack,this,&MsgControl::doCallBinaryBack);
    connect(m_DoDataThread.get(),&DoDataThread::onNetConnect,this,&MsgControl::doNetConnect);
}

MsgControl::~MsgControl(){
    m_DoDataThread = nullptr;
}

void MsgControl::publishMsg(const QString& msg){
    m_DoDataThread->sendMsg(msg);
}

void MsgControl::setStartBtnStatus(int status){
    m_StartBtnStatus = status;
    emit startBtnStatusChanged();
}

int MsgControl::getStartBtnStatus(){
    return m_StartBtnStatus;
}

void MsgControl::setErrorMsg(const QVariantMap& error){
    this->m_ErrorMsg = error;
    emit errorMsgChanged();
}

bool MsgControl::getNetConnected(){
    return m_NetConnected;
}

QVariantMap MsgControl::getErrorMsg(){
    return m_ErrorMsg;
}

void MsgControl::setFileList(const QVariantList& fileList){
    m_FileList = fileList;
    emit fileListChanged();
}

QVariantList MsgControl::getFileList(){
    return m_FileList;
}
void MsgControl::setCurFilesList(const QVariantList & list){
    m_UnPrintFiles = list;
    emit curFileslistChanged();
}

QVariantList MsgControl::getCurFilesList(){
    return m_UnPrintFiles;
}

void MsgControl::setTaskFilesList(const QVariantList &list){
    m_TaskPrintFiles = list;
    emit taskFilesListChanged();
}

QVariantList MsgControl::getTaskFilesList(){
    return m_TaskPrintFiles;
}

QString MsgControl::getCurPrintFile(){
    return m_CurPrintFile;
}

void MsgControl::setCurPrintFile(const QString &fileName){
    this->m_CurPrintFile = fileName;
    emit curPrintFileChanged();
}

void MsgControl::motorMoveForward(bool flag){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&,flag](){
        Json::Value root;
        root["button"] = "moveforward";
        if(flag){
            root["status"] = "pressed";
        }else{
            root["status"] = "release";
        }
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::motorMoveBack(bool flag){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "movebackward";
        if(flag){
            root["status"] = "pressed";
        }else{
            root["status"] = "release";
        }
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    
    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::motorMoveLeft(bool flag){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "moveleft";
        if(flag){
            root["status"] = "pressed";
        }else{
            root["status"] = "release";
        }
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    
    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::motorMoveRight(bool flag){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "moveright";
        if(flag){
            root["status"] = "pressed";
        }else{
            root["status"] = "release";
        }
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);
    
    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::motorMoveOrigin(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "goorg";
        root["status"] = "click";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::startPrint(int status){
    switch (status) {
        case 1:{
            Json::Value root;
            root["command"] = "print_start";
            root["type"] = "print";
            root["data"] = [&](){
                Json::Value root;
                root["print_list"] = [&](){
                    Json::Value root;
                    if(m_CurPrintWorkMap.size() <= 0){
                        //没有打印任务
                        return root = Json::objectValue;
                    }
                    root.append([&]{
                        Json::Value root;
                            root["uuid"] = m_CurPrintWorkMap["uuid"].toString().toStdString();
                            root["abs_filepath"] = m_CurPrintWorkMap["abs_filepath"].toString().toStdString();
                            root["filename"] = m_CurPrintWorkMap["filename"].toString().toStdString();
                            root["ripmodeid"] = m_RipMode;
                            root["modename"] = "";
                            root["printdpi"] = getPrintDpi(m_RipMode).toStdString();
                            root["printcount"] = 1;
                            root["width"] = m_CurPrintWorkMap["w"].toFloat();
                            root["height"] = m_CurPrintWorkMap["h"].toFloat();
                            root["md5id"] = m_CurPrintWorkMap["md5id"].toString().toStdString();
                            root["filesize"] = m_CurPrintWorkMap["size"].toInt();
                            root["xcopies"] = 1;
                            root["xcopyspacing"] = 0.0;
                            root["ycopies"] = 1;
                            root["ycopyspacing"] = 0.0;
                            root["scale"] = 100.0;
                        return root;}());
                    return root ;
                }();
                root["printmode"] = Json::Value("auto");
                return root;
            }();

            Json::FastWriter writer;
            const std::string json_file = writer.write(root);

            m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
            this->setStartBtnStatus(1);
        }break;
        case 2: pausePrint();break;
        case 3: resumePrint();break;
    }
}

void MsgControl::pausePrint(){
    Json::Value root;
    root["command"] = "print_pause";
    root["data"] = Json::objectValue;
    root["type"] = "print";

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::resumePrint(){
    Json::Value root;
    root["command"] = "print_resume";
    root["data"] = Json::objectValue;
    root["type"] = "print";

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::cancelPrint(){
    Json::Value root;
    Json::Value data;
    root["command"] = "print_cancel";
    root["data"] = Json::objectValue;
    root["type"] = "print";

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::clean(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "clear";
        root["status"] = "click";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::testPrint(){
    Json::Value root;
    root["type"] = "printControl";
    root["command"] = "SystemManualCommandToolButton";
    root["data"] =[&](){
        Json::Value root;
        root["button"] = "test";
        root["status"] = "click";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getUSB_FileDir(){
    Json::Value root;
    root["type"] = "system";
    root["command"] = "open_filesystem";
    root["data"] =[&](){
        Json::Value root;
        root["filepath"] = "UPan";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getWifi_FileDir(){
    Json::Value root;
    root["type"] = "system";
    root["command"] = "open_filesystem";
    root["data"] =[&](){
        Json::Value root;
        root["filepath"] = "WiFiDir";
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getNext_DirInfo(const QString& name){
    Json::Value root;
    root["type"] = "system";
    root["command"] = "get_filesystem_info";
    root["data"] =[&](){
        Json::Value root;
        root["filepath"] = name.toStdString();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::doNetConnect(const bool& flag){
    //连接服务端之后，立即获取目录 | 打印模式
    if(flag){
        getUSB_FileDir();
        getRipMode();
    }

    m_NetConnected = flag;
    emit netConnectedChanged();
}

void MsgControl::setRipMode(const QString &mode){
    if("Normal" == mode){
        m_RipMode = 0;
    }else if("High" == mode){
        m_RipMode = 1;
    }else {
        m_RipMode = 1;
    }
}

void MsgControl::selectPrintFile(const QString &filePath){
    QStringList list = filePath.split("/");
    QImage* img = ImageProvider::GetInstance()->findImage(list.last());
    if(img){
        QByteArray imageBytes;
        QBuffer buffer;
        buffer.open(QIODevice::WriteOnly);
        img->save(&buffer,"jpg");
        imageBytes.append(buffer.data());

        QString MD5;
        QByteArray str;
        str = QCryptographicHash::hash(imageBytes,QCryptographicHash::Md5);
        MD5.append(str.toHex());

        this->getPicinfo(filePath,MD5);
    }
    img = nullptr;
}

void MsgControl::getPrintWorkList(){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "print_list_read";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::getUnPrintFiles(){
    m_UnPrintFiles.clear();
    QVariantList first_list;
    for(const auto& map : m_FileList){
        if("dir" == map.toMap()["type"]) continue;
        QVariantMap tempMap = {};

        tempMap["name"] = map.toMap()["name"].toString();
        tempMap["type"] = map.toMap()["type"].toString();
        tempMap["suffix"] = map.toMap()["suffix"].toString();
        tempMap["md5id"] = map.toMap()["md5id"].toString();
        tempMap["abs_path"] = map.toMap()["abs_path"].toString();

        first_list << tempMap;
    }
    this->setCurFilesList(first_list);
}

void MsgControl::getRipMode(){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "ripserver_query_mode";
    root["data"] = Json::objectValue;

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

QString MsgControl::getPrintDpi(int modeId){
    QString dpi ;
    for(const auto& map : m_RipModeList){
        if(modeId == map.toMap()["id"].toInt()){
            dpi =  map.toMap()["dpi"].toString();
            break;
        }
    }
    return dpi;
}


void MsgControl::getPicinfo(const QString& filePath, const QString& uuid){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "ripserver_query_picinfo";
    root["data"] =[&](){
        Json::Value root;
        root["filepath"] = filePath.toStdString();
        root["uuid"] = uuid.toStdString();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::addCurPrintWork(const float& h,const float& w,const QString& path,const QString& uuid){
    //qDebug() << h << w  << path << uuid;

    m_CurPrintWorkMap.clear();
    QString fileName = path.split("/").last();
    m_CurPrintWorkMap["uuid"]      = uuid;
    m_CurPrintWorkMap["abs_filepath"]  = path;
    m_CurPrintWorkMap["filename"]  = fileName;
    m_CurPrintWorkMap["h"]         = h;
    m_CurPrintWorkMap["w"]         = w;

    for(const auto& map : m_FileList){
        if("dir" == map.toMap()["type"]) continue;

        if(fileName == map.toMap()["name"]){
            m_CurPrintWorkMap["md5id"] = map.toMap()["md5id"];
            m_CurPrintWorkMap["size"] = map.toMap()["size"];

            this->setCurPrintFile(fileName); //通知更新预览页面打印图片
            break;
        }
    }

}

void MsgControl::addPrintWork(const float& h,const float& w,const QString& path,const QString& uuid){
    //添加打印任务
    Json::Value root;
    root["command"] = "print_list_add";
    root["type"] = "print";
    root["data"] = [&](){
        Json::Value root;
        root["add_list"] = [&](){
            Json::Value root;
            root.append([&]{
                Json::Value root;
                root["uuid"] = m_CurPrintWorkMap["uuid"].toString().toStdString();
                root["abs_filepath"] = m_CurPrintWorkMap["abs_filepath"].toString().toStdString();
                root["filename"] = m_CurPrintWorkMap["filename"].toString().toStdString();
                root["ripmodeid"] = 0;
                root["printcount"] = 1;
                root["width"] = m_CurPrintWorkMap["w"].toFloat();
                root["height"] = m_CurPrintWorkMap["h"].toFloat();
                root["md5id"] = m_CurPrintWorkMap["md5id"].toString().toStdString();
                root["filesize"] = m_CurPrintWorkMap["size"].toInt();
                root["xcopies"] = 1;
                root["xcopyspacing"] = 0.0;
                root["ycopies"] = 1;
                root["ycopyspacing"] = 0.0;
                root["scale"] = 100.0;
                return root;}());
            return root ;

        }();
        root["printmode"] = Json::Value("auto");
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

void MsgControl::removePrintWork(const QString &uuid){
    Json::Value root;
    root["type"] = "print";
    root["command"] = "print_list_remove";
    root["data"] = [&]{
        Json::Value root;
        root["remove_list"] = [&]{
            Json::Value root;
            root.append([&]{
                Json::Value root;
                root["uuid"] = uuid.toStdString();
                return root;
            }());

            return root;
        }();
        return root;
    }();

    Json::FastWriter writer;
    const std::string json_file = writer.write(root);

    m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
}

//server端返回消息分发处理
/*************************************************************/

void MsgControl::doCallBinaryBack(const QByteArray& data){
    uint spi_pos = qstrlen(data.data());
    const QByteArray& json_byte = data.left(spi_pos);

    Json::Reader reader;
    Json::Value root;

    if(!reader.parse(json_byte.toStdString(), root)) {
        return;
    }

    const QString& picName = root["detail"]["filename"].asCString();
    const QImage& pic = QImage::fromData(data.right(data.size() - spi_pos - 1));

    emit onAddImage(picName,pic);
}

void MsgControl::doCallBack(const QString& msg){
    qDebug() << "msg receive : " << msg;

    Json::Reader reader;  // 读取器
    Json::Value root;

    if(!reader.parse(msg.toStdString(), root)) {
        return;
    }

    const std::string& command = root["command"].asString();

    if("print_start" == command){
          dealCallStartPrint(root);
    }else if("print_pause" == command){
          dealCallPausePrint(root);
    }else if("print_resume" == command){
          dealCallResumePrint(root);
    }else if("print_cancel" == command){
          dealCallCancelPrint(root);
    }else if("open_filesystem" == command){
          dealCallRootDirList(root);
    }else if("get_filesystem_info" == command){
          //deaCallGetFileList(root);
          dealCallRootDirList(root);
    }else if("ripserver_query_mode" == command){
          dealCallGetRipMode(root);
    }else if("ripserver_query_picinfo" == command){
          dealCallPicinfo(root);
    }else if("print_list_add" == command){
          dealCallAddPrintList(root);
    }else if("print_list_read" == command){
          dealCallPrintWorkList(root);
    }else if("print_list_remove" == command){
          dealCallRemovePrintWork(root);
    }else if("SystemManualCommandToolButton" == command){
        const std::string& btn = root["data"]["button"].asString();
        if( "clear" == btn){
            dealCallClean(root);
        }else if("test" == btn){
            dealCallTest(root);
        }else if("goorg" == btn){
            dealCallGoorg(root);
        }
    }else if("report_print_progress" == command){
            dealCallPrintProgress(root);
    }else if("report_rip_progress" == command){
            dealCallRipProgress(root);
    }else if("report_warn_message" == command){
            dealCallWarnMessage(root);
    }else{
        return;  //增加执行健壮
    }
}

void MsgControl::dealCallStartPrint(const Json::Value& value){
    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        this->setStartBtnStatus(2);
    }else{
        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);
    }
}

void MsgControl::dealCallPausePrint(const Json::Value& value){
    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        this->setStartBtnStatus(3);
        msgMap["msg"]   = "已暂停打印！";
        msgMap["type"]  = "tip";
    }else{
        msgMap["type"]  = "error";
    }

    this->setErrorMsg(msgMap);
}

void MsgControl::dealCallResumePrint(const Json::Value& value){

    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        this->setStartBtnStatus(2);
        msgMap["msg"]   = "已恢复打印！";
        msgMap["type"]  = "tip";
    }else{
        msgMap["type"]  = "error";
    }

    this->setErrorMsg(msgMap);
}

void MsgControl::dealCallCancelPrint(const Json::Value &value){
    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        this->setStartBtnStatus(1);
        msgMap["msg"]   = "已取消本次打印！";
        msgMap["type"]  = "tip";
        this->setErrorMsg(msgMap);
    }else{
        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);
    }
}

void MsgControl::dealCallClean(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["title"]  = value["data"]["button"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        msgMap["msg"]   = "清洗完成！";
        msgMap["type"]  = "tip";
    }else{
        msgMap["type"]  = "error";
    }

    this->setErrorMsg(msgMap);
}

void MsgControl::dealCallTest(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["title"]  = value["data"]["button"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        msgMap["msg"]   = "测试打印完成！";
        msgMap["type"]  = "tip";
    }else{
        //msgMap["msg"]   = "waiting...";
        msgMap["type"]  = "error";
    }

    this->setErrorMsg(msgMap);
}

void MsgControl::dealCallGoorg(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["title"]  = value["data"]["button"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        msgMap["msg"]   = "回原点完成！";
        msgMap["type"]  = "tip";
    }else{
        msgMap["type"]  = "error";
    }

    this->setErrorMsg(msgMap);
}

void MsgControl::dealCallRootDirList(const Json::Value& value){
    //清空文件列表
    m_FileList.clear();
    const Json::Value& data = value["data"]["data"];
    QVariantList first_list;
    for(int i = 0 ; i < (int)data.size() ; i++){
        QVariantMap tempMap = {};
        tempMap["name"] = data[i]["name"].asCString();
        tempMap["type"] = data[i]["info"]["type"].asCString();
        tempMap["suffix"] = data[i]["info"]["suffix"].asCString();
        tempMap["md5id"] = data[i]["info"]["md5id"].asCString();
        tempMap["uuid"] = data[i]["info"]["uuid"].asCString();
        tempMap["abs_path"] = data[i]["info"]["abs_path"].asCString();

        if("file" == tempMap["type"]){
            tempMap["size"] = data[i]["info"]["filesize"].asInt();
        }

        first_list << tempMap;
    }

    this->setFileList(first_list);

    //开始获取缩略图
    this->getSmallPic();
}

void MsgControl::deaCallGetFileList(const Json::Value& value){

}

void MsgControl::getSmallPic(){
    if(m_FileList.size() <= 0) return;

    for(const auto& map : m_FileList){
        if("dir" == map.toMap()["type"]) continue;

        Json::Value root;
        root["type"] = "system";
        root["command"] = "filesystem_geticon";
        root["data"] =[&](){
            Json::Value root;
            root["filename"] = QString(map.toMap()["name"].toString()).toStdString();
            root["md5id"] = QString(map.toMap()["md5id"].toString()).toStdString();
            return root;
        }();

        Json::FastWriter writer;
        const std::string json_file = writer.write(root);
        m_DoDataThread->sendMsg(QString::fromStdString(json_file).trimmed());
    }
}

void MsgControl::dealCallGetRipMode(const Json::Value & value){

    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(!msgMap["flag"].toBool()){
        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);
    }else{
        const Json::Value& data = value["data"]["modes"];
        QVariantList first_list;
        for(int i = 0 ; i < (int)data.size() ; i++){
            QVariantMap tempMap1 = {};
            tempMap1["id"] = data[i]["id"].asInt();
            tempMap1["name"] = data[i]["name"].asCString();
            tempMap1["dpi"] = data[i]["dpi"].asCString();
            tempMap1["ink"] = data[i]["ink"].asCString();
            tempMap1["paper"] = data[i]["paper"].asCString();

            m_RipModeList << tempMap1;
        }
    }
}

void MsgControl::dealCallPicinfo(const Json::Value &value){
    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(!msgMap["flag"].toBool()){
        msgMap["type"]  = "error";
        this->setErrorMsg(msgMap);
    }else{
        float height = value["data"]["picinfo"]["height"].asFloat();
        float width = value["data"]["picinfo"]["width"].asFloat();
        QString filePath = value["data"]["picinfo"]["filepath"].asCString();
        QString uuid = value["data"]["picinfo"]["uuid"].asCString();

        addCurPrintWork(height,width,filePath,uuid);

        this->addPrintWork(height,width,filePath,uuid);
    }
}

void MsgControl::dealCallAddPrintList(const Json::Value &value){
    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        msgMap["type"]  = "tip";
        msgMap["msg"] = "添加成功！";
    }else{
        msgMap["type"]  = "error";
    }

    this->setErrorMsg(msgMap);
}

void MsgControl::dealCallPrintWorkList(const Json::Value & value){

    m_TaskPrintFiles.clear();
    const Json::Value& data = value["data"]["printlist"];
    QVariantList first_list;
    for(int i = 0 ; i < (int)data.size() ; i++){
        QVariantMap tempMap = {};
        tempMap["name"] = data[i]["filename"].asCString();
        tempMap["type"] = "file";
        tempMap["md5id"] = data[i]["md5id"].asCString();
        tempMap["uuid"] = data[i]["uuid"].asCString();
        tempMap["abs_path"] = data[i]["abs_filepath"].asCString();

        first_list << tempMap;
    }

    this->setTaskFilesList(first_list);
}

void MsgControl::dealCallRemovePrintWork(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    msgMap["msg"]   = value["data"]["message"].asCString();
    msgMap["flag"]  = value["data"]["ret"].asBool();

    if(msgMap["flag"].toBool()){
        msgMap["type"]  = "tip";
        msgMap["msg"] = "删除成功！";
    }else{
        msgMap["type"]  = "error";
    }

    this->setErrorMsg(msgMap);
}

void MsgControl::dealCallPrintProgress(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    const QString& state  = value["data"]["state"].asCString();

    if("wrong" == state){
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        msgMap["msg"]   = value["data"]["message"].asCString();

        this->setErrorMsg(msgMap);
    }else{
        qDebug() << "PrintProgress: " << value["data"]["progress"].asInt();
    }
}

void MsgControl::dealCallRipProgress(const Json::Value & value){
    QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    const QString& state  = value["data"]["state"].asCString();

    if("wrong" == state){
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        msgMap["msg"]   = value["data"]["message"].asCString();

        this->setErrorMsg(msgMap);
    }else{
        qDebug() << "RipProgress: " << value["data"]["progress"].asInt();
    }
}

void MsgControl::dealCallWarnMessage(const Json::Value & value){
    /** to do
      */

    /*QVariantMap msgMap;
    msgMap["title"]  = value["command"].asCString();
    const QString& state  = value["data"]["state"].asCString();

    if("wrong" == state){
        msgMap["flag"] = false;
        msgMap["type"]  = "error";
        msgMap["msg"]   = value["data"]["message"].asCString();

        this->setErrorMsg(msgMap);
    }else{
        qDebug() << "RipProgress: " << value["data"]["progress"].asInt();
    }*/
}
